﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Cofe.Core;
using Cofe.Core.Implements;
using Cofe.Web.Interfaces;
using Newtonsoft.Json.Linq;

namespace Cofe.Web.Implements
{
    [Export(typeof(ICofeService))]
    [ServicePriority(ServicePriorityAttribute.DefaultPriority_COFEWS)]
    public class EntryResponseFormatter : IHttpResponseMessageFormatter
    {
        public bool CanCreateResponse(HttpRequestMessage request,
            object returnVal, ParameterDic pd, ResponseFormatterInfo info)
        {
            return (returnVal is CofeSystemInfo || returnVal is IEnumerable<ICofeSystemInfo>
                || returnVal is IEnumerable<CofeSystemInfo> || returnVal is WebEntryList);
        }

        public HttpResponseMessage CreateResponse(HttpRequestMessage request,
            object returnVal, ParameterDic pd, ResponseFormatterInfo info)
        {
            HttpResponseMessage response = null;

            if (returnVal is CofeSystemInfo)
            {
                response = request.CreateResponse<JObject>(info.StatusCode,
                    CofeServices.EntrySerializer.WriteEntry(returnVal as CofeSystemInfo, true));
            }
            else
            {
                IEnumerable<CofeSystemInfo> entries;
                if (returnVal is WebEntryList)
                    entries = (returnVal as WebEntryList).Entries;
                else if (returnVal is IEnumerable<CofeSystemInfo>)
                    entries = returnVal as IEnumerable<CofeSystemInfo>;
                else if (returnVal is IEnumerable<ICofeSystemInfo>)
                    entries = from ei in (returnVal as IEnumerable<ICofeSystemInfo>)
                              select ei as CofeSystemInfo;
                else throw new NotSupportedException();

                var retEntryList = new WebEntryList() { Entries = entries, Parameters = pd };
                
                response = request.CreateResponse<JObject>(HttpStatusCode.OK, 
                    CofeServices.EntrySerializer.WriteEntryList(retEntryList, false));
            }

            return response;
        }
    }
}
